<template>
  <div class="home">
    <button ref="buttonRef" id="button" aria-describedby="tooltip">I'm a button</button>
    <div ref="tooltipRef" id="tooltip" role="tooltip">
      <div id="arrow" data-popper-arrow></div>
      I'm a tooltip
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, nextTick } from 'vue'
import { createPopper } from '@popperjs/core'

export default defineComponent({
  name: 'Home',
  components: {},
  setup() {
    const buttonRef = ref<Element>()
    const tooltipRef = ref<HTMLElement>()
    onMounted(() => {
      const popperInstance = createPopper(buttonRef.value as Element, tooltipRef.value as HTMLElement, {
        modifiers: [
          {
            name: 'offset',
            options: {
              offset: [0, -25],
            },
          },
        ],
      })
      async function show() {
        tooltipRef.value?.setAttribute('data-show', '')

        // Enable the event listeners
        popperInstance.setOptions({
          modifiers: [
            { name: 'eventListeners', enabled: true },
            {
              name: 'offset',
              options: {
                offset: [0, 8],
              },
            },
          ],
        })

        // We need to tell Popper to update the tooltip position
        // after we show the tooltip, otherwise it will be incorrect
        popperInstance.update()
      }

      async function hide() {
        tooltipRef.value?.removeAttribute('data-show')
        // Disable the event listeners
        popperInstance.setOptions({
          modifiers: [
            { name: 'eventListeners', enabled: false },
            {
              name: 'offset',
              options: {
                offset: [0, 8],
              },
            },
          ],
        })
      }

      const showEvents = ['mouseenter', 'focus']
      const hideEvents = ['mouseleave', 'blur']

      showEvents.forEach((event) => {
        buttonRef.value?.addEventListener(event, show)
      })

      hideEvents.forEach((event) => {
        buttonRef.value?.addEventListener(event, hide)
      })
    })
    return { buttonRef, tooltipRef }
  },
})
</script>

<style lang="scss" scoped>
#tooltip {
  background: #333;
  color: white;
  font-weight: bold;
  padding: 4px 8px;
  font-size: 13px;
  border-radius: 4px;
  // display: none;
}

#tooltip[data-show] {
  // display: block;
}

#arrow,
#arrow::before {
  position: absolute;
  width: 8px;
  height: 8px;
  background: inherit;
}

#arrow {
  visibility: hidden;
}

#arrow::before {
  visibility: visible;
  content: '';
  transform: rotate(45deg);
}

#tooltip[data-popper-placement^='top'] > #arrow {
  bottom: -4px;
}

#tooltip[data-popper-placement^='bottom'] > #arrow {
  top: -4px;
}

#tooltip[data-popper-placement^='left'] > #arrow {
  right: -4px;
}

#tooltip[data-popper-placement^='right'] > #arrow {
  left: -4px;
}
.home {
  padding-bottom: 1000px;
}
</style>
